package com.streamer.app

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.fragment.app.commit
import com.alivc.live.pusher.AlivcLivePusher
import com.alivc.live.pusher.AlivcLivePushConfig
import com.bumptech.glide.Glide
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.streamer.app.bean.GiftData
import com.streamer.app.bean.LiveBean
import com.streamer.app.bean.MessageBean
import com.streamer.app.fragment.LiveVideoFragment
import com.streamer.app.fragment.PPTWhiteboardFragment
import com.streamer.app.utils.MqttManager
import com.streamer.app.utils.UserManager
import com.streamer.app.utils.UserManager.getLocalUser
import com.streamer.app.utils.api.ViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlin.random.Random

/**
 * PPT课件白板直播
 */
class ThreeScreenLiveActivity : BaseActivity(), MqttManager.MessageCallback {
    private lateinit var llGift: LinearLayout
    private lateinit var centerEndedContent: View
    private lateinit var ivGiftIcon: ImageView
    private lateinit var ivClose: ImageView
    private lateinit var tvGiftName: TextView

    private lateinit var whiteboardContainerId: View
    private lateinit var liveContainerId: View
    private var mliveData: LiveBean? = null
    private var viewMode = ViewModel()

    // 风险提示文本相关
    private lateinit var riskAlertTextView: TextView
    private lateinit var root: View
    private var riskAlertScrollJob: Job? = null
    private var riskAlertText = ""
    private var displayMode = 2 // 1:底部循环滚动, 2:全屏滚动
    private var displayFontSize = 14f
    private var displayFontColour = "#FFFFFF"
    private var displayScrollSpeed = 30 // 滚动速度(毫秒)
    private var displayTransparency = 0.8f // 透明度

    // MQTT相关
    private lateinit var mqttManager: MqttManager
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_three_screen_live)
        riskAlertTextView = findViewById(R.id.tv_risk_alert)
        root = findViewById(R.id.root)

        llGift = findViewById(R.id.llGift)
        ivClose = findViewById(R.id.ivClose)
        centerEndedContent = findViewById(R.id.center_ended_content)
        ivGiftIcon = findViewById(R.id.ivGiftIcon)
        tvGiftName = findViewById(R.id.tvGiftName)
        initViews()
        setupSplitScreens()

        viewMode.getLiveInfo()
        viewMode.LiveInfoLV.observe(this@ThreeScreenLiveActivity) {
            if (it != null) {
                mliveData = it
                if (mliveData?.useState == 2) {
                    centerEndedContent.visibility = View.VISIBLE

                }
                // 处理风险提示文本 - 优先使用 riskAlertContent
                var riskContent: String? = null
                // 首先尝试从 riskAlertContent 获取
                riskContent = it.riskAlertContent as? String
                // 如果 riskAlertContent 为空，尝试从 liveCommonConfig 中获取
                if (riskContent.isNullOrEmpty() && it.liveCommonConfig != null) {
                    try {
                        val configStr = it.liveCommonConfig.toString()
                        // 尝试解析为 JSON
                        val jsonObject = org.json.JSONObject(configStr)
                        riskContent = jsonObject.optString("riskAlertContent")
                    } catch (e: Exception) {
                    }
                }

                // 如果还是没有，尝试从 liveConfig 中获取
                if (riskContent.isNullOrEmpty()) {
                    riskContent = it.liveConfig?.riskAlertContent
                    Log.d("RiskAlert", "riskContent from liveConfig: $riskContent")
                }


                if (riskContent != null && riskContent.isNotEmpty()) {
                    riskAlertText = riskContent
                } else {
                    // 如果没有风险内容，使用测试文本
                    riskAlertText =
                        "第一行：这是默认测试文本\n第二行：用于验证多行滚动效果\n第三行：请长按美颜按钮测试更多功能"
                }

                // 应用 liveCommonConfig 中的配置
                try {
                    // 使用反射获取 liveCommonConfig 对象的属性
                    val configClass = it.liveCommonConfig.javaClass

                    // 获取 displayMode
                    val displayModeField = configClass.getDeclaredField("displayMode")
                    displayModeField.isAccessible = true
                    val modeValue = displayModeField.get(it.liveCommonConfig)
                    displayMode = (modeValue as? Number)?.toInt() ?: 2

                    // 获取 displayFontSize
                    val fontSizeField = configClass.getDeclaredField("displayFontSize")
                    fontSizeField.isAccessible = true
                    val fontSizeValue = fontSizeField.get(it.liveCommonConfig)
                    displayFontSize = (fontSizeValue as? Number)?.toFloat() ?: 16f


                    // 获取 displayFontColour
                    val fontColourField = configClass.getDeclaredField("displayFontColour")
                    fontColourField.isAccessible = true
                    val fontColourValue = fontColourField.get(it.liveCommonConfig)
                    displayFontColour = fontColourValue as? String ?: "#FFFFFF"


                    // 获取 displayScrollSpeed
                    val scrollSpeedField = configClass.getDeclaredField("displayScrollSpeed")
                    scrollSpeedField.isAccessible = true
                    val scrollSpeedValue = scrollSpeedField.get(it.liveCommonConfig)
                    displayScrollSpeed = (scrollSpeedValue as? Number)?.toInt() ?: 50


                    // 获取 displayTransparency
                    val transparencyField = configClass.getDeclaredField("displayTransparency")
                    transparencyField.isAccessible = true
                    val transparencyValue = transparencyField.get(it.liveCommonConfig)
                    displayTransparency =
                        (transparencyValue as? Number)?.toFloat()?.div(100f) ?: 0.8f


                } catch (e: Exception) {
                    Log.d(
                        "RiskAlert", "Failed to get liveCommonConfig properties: ${e.message}"
                    )
                }
            }

            // 确保 displayMode 是有效值
            if (displayMode != 1 && displayMode != 2) {
                displayMode = 2 // 默认使用全屏滚动模式
            }

            // 如果 liveCommonConfig 中没有配置，尝试从 liveConfig 中获取
            if (displayMode == 1 && displayFontSize == 16f && displayFontColour == "#FFFFFF") {
                it?.liveConfig?.let { liveConfig ->
                    liveConfig.displayMode?.let { mode ->
                        displayMode = mode
                    }
                    liveConfig.displayFontSize?.let { size ->
                        displayFontSize = size.toFloat()
                    }
                    liveConfig.displayFontColour?.let { color ->
                        displayFontColour = color
                    }
                    liveConfig.displayScrollSpeed?.let { speed ->
                        displayScrollSpeed = speed
                    }
                    liveConfig.displayTransparency?.let { transparency ->
                        displayTransparency = transparency / 100f
                    }
                }

                updateRiskAlertDisplay()
                setupMqtt()
            }
        }

        ivClose.setOnClickListener {
            val intent = Intent(this@ThreeScreenLiveActivity, LoginActivity::class.java)
            startActivity(intent)
            UserManager.clearData()
            finish()
        }
    }

    private fun initViews() {

        whiteboardContainerId = findViewById(R.id.container_whiteboard)
        liveContainerId = findViewById(R.id.container_live)
    }

    private fun setupSplitScreens() {
        supportFragmentManager.commit {
            replace(R.id.container_whiteboard, PPTWhiteboardFragment.newInstance(null))
            replace(R.id.container_live, LiveVideoFragment.newInstance())
        }
    }

    override fun onDestroy() {
        super.onDestroy()
    }

    fun endLive() {
        centerEndedContent.visibility = View.VISIBLE
        val intent = Intent(this@ThreeScreenLiveActivity, LoginActivity::class.java)
        startActivity(intent)
        UserManager.clearData()
        finish()
    }

    /**
     * 从 LiveVideoFragment 触发 PPTWhiteboardFragment 的录制开始
     */
    fun triggerWhiteboardRecording(pushLive3PUrl: String) {
        Log.d("ThreeScreenLiveActivity", "triggerWhiteboardRecording called with URL: $pushLive3PUrl")
        
        // 获取 PPTWhiteboardFragment
        val whiteboardFragment = supportFragmentManager.fragments
            .find { it is PPTWhiteboardFragment } 
            as? PPTWhiteboardFragment
        

        whiteboardFragment?.let { fragment ->
            // 调用 PPTWhiteboardFragment 的录制方法，传递推流地址
            fragment.startRecordingFromVideoFragment(pushLive3PUrl)
        } ?: run {
            Log.w("ThreeScreenLiveActivity", "PPTWhiteboardFragment not found")
        }
    }
    

    private fun setupMqtt() {
        mqttManager = MqttManager.getInstance()
        mqttManager.addMessageCallback(this)

        val random6Digit = Random.nextInt(100000, 1000000)
        // 连接MQTT
        mqttManager.connect(
            this@ThreeScreenLiveActivity,
            "${mliveData?.liveRoomNo + "," + mliveData?.id + "," + getLocalUser()?.id + ",5" + "," + random6Digit}"
        ) { success, message ->
            runOnUiThread {
                if (success) {
                    Log.d("LiveStreamActivity", "MQTT connected: $message")

                    // 订阅直播相关主题
                    subscribeToLiveTopics()
                } else {
                    Log.e("LiveStreamActivity", "MQTT connection failed: $message")

                }
            }
        }
    }


    private fun subscribeToLiveTopics() {
        // 订阅直播相关主题
        val liveRoomNo = mliveData?.id ?: ""
        val topics = listOf(
            "chat/$liveRoomNo"
        )

        topics.forEach { topic ->
            mqttManager.subscribe(topic) { success, message ->

            }
        }
    }

    override fun onMessageReceived(topic: String, message: String) {

        runOnUiThread {
            handleLiveMessage(message)
        }
    }

    override fun onConnectionStatusChanged(connected: Boolean) {
    }

    private fun handleLiveMessage(message: String) {
        try {
            val gson = Gson()
            val chatMessage = gson.fromJson(message, MessageBean::class.java)

            when (chatMessage.type) {
                1 -> { /* JOIN(1) - 进入房间 */
                }

                2 -> { /* LEAVE(2) - 离开房间 */
                }

                3 -> { // MSG(3) - 普通消息
                    // 添加到弹幕适配器


                }

                4 -> { /* SYSTEM(4) - 系统消息 */
                }

                5 -> { /* DRAW(5) - 抽奖倒计时 */
                }

                6 -> { /* COUPON(6) - 优惠券倒计时 */
                }

                7 -> { /* TAUGHT(7) - 商品讲解 */
                }

                8 -> { /* NOTICE(8) - 公告 */
                }

                9 -> { /* COUPON_RECEIVE(9) - 优惠券领取 */
                }

                10 -> { /* DRAW_USER(10) - 抽奖完成通知 */
                }

                11 -> { /* MSG_CONCEAL(11) - 消息隐藏 */
                }

                12 -> { /* BESTOW_GIFT(12) - 赠送礼物 */

                    Log.d("xxxx", "赠送礼物=====+$chatMessage")
                    llGift.visibility = View.VISIBLE
                    val gson = Gson()
                    val giftData = gson.fromJson(chatMessage.content, GiftData::class.java)
                    tvGiftName.text = giftData.nickName + "赠送了一个" + giftData.giftName
                    ivGiftIcon.apply {
                        Glide.with(this).load(giftData.effectUrl).into(this)
                    }
                    llGift.postDelayed({
                        llGift.visibility = View.GONE
                    }, 5000)
                }

                13 -> { /* DEFRIEND(13) - 踢出直播间 */
                }

                14 -> { /* POINTS_ACQUISITION(14) - 获取积分 */
                }

                15 -> { /* CANCEL_TAUGHT(15) - 取消讲解 */
                }

                16 -> { /* LIKE(16) - 点赞 */

                }

                17 -> { /* PUTAWAY(17) - 商品上架 */
                }

                18 -> { /* CONFIG_STATUS_UPDATE(18) - 直播配置状态更新 */
                }

                19 -> { /* THE_USER_IS_BUYING(19) - 正在购买商品 */
                }

                20 -> { /* POPULARITY(20) - 直播间人气推送 */

                }

                else -> { /* 未知类型 */
                }
            }

        } catch (e: JsonSyntaxException) {
            Log.e("LiveStreamActivity", "Error parsing JSON message: ${e.message}")
            Log.e("LiveStreamActivity", "Raw message: $message")
        } catch (e: Exception) {
            Log.e("LiveStreamActivity", "Error handling message: ${e.message}")
            Log.e("LiveStreamActivity", "Raw message: $message")
        }
    }


    private fun updateRiskAlertDisplay() {


        riskAlertTextView.text = riskAlertText
        riskAlertTextView.textSize = displayFontSize
        riskAlertTextView.setTextColor(android.graphics.Color.parseColor(displayFontColour))
        riskAlertTextView.alpha = displayTransparency
        riskAlertTextView.visibility = View.VISIBLE


        riskAlertTextView.bringToFront()
        riskAlertTextView.elevation = 20f
        riskAlertTextView.visibility = View.VISIBLE


        // 清除可能影响 y 定位的顶部 margin（不依赖具体父布局类型）
        (riskAlertTextView.layoutParams as? ViewGroup.MarginLayoutParams)?.let { lp ->
            if (lp.topMargin != 0) {
                lp.topMargin = 0
                riskAlertTextView.layoutParams = lp
            }
        }

        // 根据显示模式启动滚动（强制按当前需求使用全屏行滚动）
        Log.d("RiskAlert", "=== 准备启动滚动，displayMode = $displayMode（强制按2处理） ===")
        when (displayMode) {
            1 -> {
                Log.d("RiskAlert", "Starting bottom scroll (单行循环滚动)")
                startBottomScroll()
            }

            2 -> {
                Log.d("RiskAlert", "Starting full screen scroll (5行滚动)")
                startFullScreenScroll()
            }

            else -> {
                // 强制全屏行滚动
                startFullScreenScroll()
            }
        }
    }

    private fun startBottomScroll() {
        stopRiskAlertScroll()
        riskAlertScrollJob = CoroutineScope(Dispatchers.Main).launch {
            val textView = riskAlertTextView
            val text = textView.text.toString()
            val textWidth = textView.paint.measureText(text)
            val screenWidth = textView.context.resources.displayMetrics.widthPixels


            // 调整滚动速度，确保不会太快
            val scrollSpeed = if (displayScrollSpeed < 10) 50 else displayScrollSpeed


            var currentX = -textWidth.toFloat() // 从左边开始

            while (isActive) {
                textView.translationX = currentX
                currentX += 1f // 每次移动1像素，从左往右

                if (currentX >= screenWidth) {
                    currentX = -textWidth.toFloat() // 回到左边重新开始
                    // 滚动完成后，停留一下再重新开始
                    delay(2000) // 停留2秒
                }

                delay(scrollSpeed.toLong())
            }
        }
    }

    private fun startFullScreenScroll() {
        stopRiskAlertScroll()
        riskAlertScrollJob = CoroutineScope(Dispatchers.Main).launch {
            val textView = riskAlertTextView
            val text = textView.text.toString()

            // 使用根布局高度，计算可容纳的“行数”（按 TextView 实际高度划分）
            val rootView = findViewById<View>(android.R.id.content)
            val containerHeight = (rootView.height.takeIf { it > 0 }
                ?: textView.context.resources.displayMetrics.heightPixels)

            // 确保拿到 TextView 的高度
            var tvHeight = textView.height
            if (tvHeight <= 0) {
                textView.measure(
                    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
                )
                tvHeight = textView.measuredHeight
            }
            if (tvHeight <= 0) {
                // 兜底：用字体大小粗略估算行高
                tvHeight = (displayFontSize * resources.displayMetrics.density * 1.8f).toInt()
                    .coerceAtLeast(1)
            }
            // 按需求固定分成5行显示，更符合期望效果
            val rows = 5
            val lineHeightPx = containerHeight / rows.toFloat()
            Log.d(
                "RiskAlert",
                "Full screen scroll started, containerHeight=$containerHeight, tvHeight=$tvHeight, rows=$rows, lineHeightPx=$lineHeightPx"
            )

            // 调整滚动速度
            val scrollSpeed = if (displayScrollSpeed < 10) 50 else displayScrollSpeed
            Log.d("RiskAlert", "Adjusted scroll speed: $scrollSpeed")

            var rowIndex = 0
            val screenWidth = textView.context.resources.displayMetrics.widthPixels

            while (isActive) {
                // 计算当前行的Y坐标（行中心对齐到该行区域中部）
                // 将 TextView 垂直居中到该行区域内
                val rowTop = rowIndex * lineHeightPx
                val centeredTop = (rowTop + (lineHeightPx - tvHeight) / 2f)
                val clampedY = centeredTop.coerceIn(
                    0f, (containerHeight - tvHeight).toFloat().coerceAtLeast(0f)
                )
                Log.d("RiskAlert", "=== 显示第${rowIndex + 1}/$rows 行，y=$clampedY ===")

                // 将 TextView 移到该行
                textView.y = clampedY
                textView.translationX = 0f

                // 计算文本宽度
                val textWidth = textView.paint.measureText(text)
                Log.d(
                    "RiskAlert",
                    "行${rowIndex + 1} - textWidth=$textWidth, screenWidth=$screenWidth"
                )

                // 水平滚动：从左完全外到右完全外
                var currentX = -textWidth.toFloat()
                val endX = screenWidth.toFloat()
                while (isActive && currentX < endX) {
                    textView.translationX = currentX
                    currentX += 1f
                    delay(scrollSpeed.toLong())
                }
                textView.translationX = 0f
                Log.d("RiskAlert", "行${rowIndex + 1} 滚动完成")

                // 切换到下一行；到达底部后回到顶部
                rowIndex = (rowIndex + 1) % rows
                delay(500)
            }
        }
    }

    private fun stopRiskAlertScroll() {
        riskAlertScrollJob?.cancel()
        riskAlertScrollJob = null
        riskAlertTextView.translationX = 0f
    }

}
